package com.link.base.tencent.ocr.util;

import com.alibaba.fastjson.JSONObject;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.HttpRequestUtil;
import org.apache.commons.lang.StringUtils;

/**
 * 腾讯云文字识别工具类
 *
 * @author ouyangzhenqiang
 * @date 2018/12/29
 */
public class OcrUtil {

    /**
     * 名片识别
     *
     * @author ouyangzhenqiang
     * @date 2018/12/29
     * @param authorization 签名
     * @param appId         接入项目的唯一标识
     * @param bucket        图片空间
     * @param imgUrl        图片访问链接
     */
    public static String businessCard(String authorization, String appId, String bucket, String imgUrl) throws Exception {
        if (StringUtils.isBlank(authorization)) {
            throw new ServiceException("OCR-005");
        }
        if (StringUtils.isBlank(appId)) {
            throw new ServiceException("OCR-006");
        }
        if (StringUtils.isBlank(bucket)) {
            throw new ServiceException("OCR-007");
        }
        if (StringUtils.isBlank(imgUrl)) {
            throw new ServiceException("OCR-008");
        }
        String url = "https://recognition.image.myqcloud.com/ocr/businesscard";
        String param = "{\"appid\":\"" + appId + "\",\"bucket\":\"" + bucket + "\",\"url_list\":[\"" + imgUrl + "\"]}";
        String resultStr = HttpRequestUtil.jsonPostThrowException(url, param, authorization);
        exception(resultStr);
        return resultStr;
    }


    /**
     * 身份证识别
     *
     * @author ouyangzhenqiang
     * @date 2018/12/29
     * @param authorization 签名
     * @param appId         接入项目的唯一标识
     * @param bucket        图片空间
     * @param imgUrl        图片访问链接
     */
    public static String idCard(String authorization, String appId, String bucket, String imgUrl) throws Exception {
        if (StringUtils.isBlank(authorization)) {
            throw new ServiceException("OCR-005");
        }
        if (StringUtils.isBlank(appId)) {
            throw new ServiceException("OCR-006");
        }
        if (StringUtils.isBlank(bucket)) {
            throw new ServiceException("OCR-007");
        }
        if (StringUtils.isBlank(imgUrl)) {
            throw new ServiceException("OCR-008");
        }
        String url = "https://recognition.image.myqcloud.com/ocr/idcard";
        String param = "{\"appid\":\"" + appId + "\",\"bucket\":\"" + bucket + "\",\"card_type\": 0, \"url_list\":[\"" + imgUrl + "\"]}";
        String resultStr = HttpRequestUtil.jsonPostThrowException(url, param, authorization);
        exception(resultStr);
        return resultStr;
    }

    /**
     * 接口异常处理
     */
    public static void exception(String jsonResult) throws Exception {
        JSONObject jsonObj = JSONObject.parseObject(jsonResult);
        try {
            jsonObj.getJSONArray("result_list");
        } catch (Exception e) {
            throw new Exception(jsonObj.getString("code") + "-" + jsonObj.getString("message"));
        }
    }
}
